package com.sixth.service.impl;

import com.sixth.core.entity.CareHistory;
import com.sixth.core.vo.R;
import com.sixth.dto.CareOrderDto;
import com.sixth.dto.OrderDetailsDto;
import com.sixth.mapper.CareHistoryMapper;
import com.sixth.service.CareHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 李劲锋
 * @create: 2024-08-15 11:40
 **/
@Service
public class CareHistoryServiceImpl implements CareHistoryService {
    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Override
    public R<List<CareHistory>> selectById(String registrationId) {
        List<CareHistory> list = careHistoryMapper.selectByIdAll(registrationId);
        return R.ok(list);
    }

    @Override
    public R<List<CareHistory>> selectByIdFee(String registrationId) {
        List<CareHistory> list = careHistoryMapper.selectByIdAllFee(registrationId);
        return R.ok(list);
    }

    @Override
    public R orderDetails(String chId) {
        // 获取所有相关的 OrderDetailsDto 对象
        List<OrderDetailsDto> orderDetailsDtos = careHistoryMapper.selectByChIdAll(chId);

        if (orderDetailsDtos == null || orderDetailsDtos.isEmpty()) {
            return R.error("No records found");
        }

        // 初始化合并后的结果
        OrderDetailsDto mergedResult = new OrderDetailsDto();

        // 保留第一个 careHistory
        mergedResult.setCareHistory(orderDetailsDtos.get(0).getCareHistory());

        // 合并 careOrderDtos 和计算 totalMoney
        List<CareOrderDto> mergedCareOrderDtos = new ArrayList<>();
        int totalMoney = 0;
        String orderStatus = null;

        for (OrderDetailsDto dto : orderDetailsDtos) {
            mergedCareOrderDtos.addAll(dto.getCareOrderDtos());
            totalMoney += dto.getTotalMoney();
            if (orderStatus == null) {
                orderStatus = String.valueOf(dto.getOrderStatus());
            }
        }

        // 设置合并后的 careOrderDtos、总金额和状态
        mergedResult.setCareOrderDtos(mergedCareOrderDtos);
        mergedResult.setTotalMoney(totalMoney);

        // 状态转换，如果状态为 "0" 则传递为 1，否则保持原值
        if ("0".equals(orderStatus)) {
            mergedResult.setOrderStatus(0);
        } else if ("1".equals(orderStatus)) {
            mergedResult.setOrderStatus(1);
        } else if ("3".equals(orderStatus)) {
            mergedResult.setOrderStatus(5);
        } else if ("5".equals(orderStatus)) {
            mergedResult.setOrderStatus(6);
        } else {
            mergedResult.setOrderStatus(Integer.parseInt(orderStatus));
        }

        return R.ok(mergedResult);
    }


}
